# -*- coding: utf-8 -*-
import os
from PIL import Image
import simplejson as json

import tileimage
import imageutil

class TileSet(object):
    """A tile set is a list of tiny images (called tiles). Each image
    on the list should be an instance of gtk.gdk.Pixbuf with the same
    size.
    """
    def __init__(self, name, pixbufs):
        """Create a tile set from a list of pixbufs.
        """
        self.name = name
        self.tilelist = list(pixbufs)

        # Take the tile size from the first pixbuf on the list.
        first = self.tilelist[0]
        self.tile_width, self.tile_height = (first.get_width(),
                                             first.get_height())


    @property
    def num_tiles(self):
        return len(self.tilelist)

    @property
    def tile_size(self):
        return (self.tile_width, self.tile_height)

    def __getitem__(self, i):
        return self.tilelist[i]

    def __iter__(self):
        return iter(self.tilelist)

    def save(self, base_path=os.curdir):
        """Save a tileset to disc to the given filename.
        """
        json_path = os.path.join(base_path, "%s.ts" % self.name)
        img_name = "%s.png" % self.name

        metadata = {
            "name": self.name,
            "type": self.__class__.__name__,
            "image": img_name,
            "tile_width": self.tile_width,
            "tile_height": self.tile_height,
            }

        json.dump(metadata, open(json_path, "w"))
        self.make_image(os.path.join(base_path, img_name))

    def make_image(self, filename, cols=5):
        """Make a tile set image.
        """
        tiles = [imageutil.pixbuf_to_pil(pb)
                 for pb in self.tilelist]
        im = tileimage.tiles_image(tiles, cols)
        im.save(filename)


def from_file(filename):
    """Load a previously saved tileset from disc.
    """
    metadata = json.load(open(filename, "r"))
    base_path = os.path.dirname(filename)

    tile_size = metadata["tile_width"], metadata["tile_height"]
    return from_image(metadata["name"],
                      os.path.join(base_path, metadata["image"]),
                      tile_size)

def from_image(name, image_file, tilesize, spacing=(0,0), border=(0,0,0,0)):
    """Make tiles from a image file.
    """
    pil_tiles = tileimage.make_tiles(Image.open(image_file),
                                     tilesize, spacing, border)
    pixbufs = [imageutil.pil_to_pixbuf(im) for im in pil_tiles]
    return TileSet(name, pixbufs)
